<template>
  <div>
    <el-row>
      <el-col :offset="4" :span="10" class="search">
        <el-autocomplete
          @select="handleSelect"
          v-model="search"
          :select-when-unmatched="true"
          value-key="name"
          :fetch-suggestions="querySearch"
          prefix-icon="el-icon-search"
          placeholder="请输入商品名称"
          clearable
        >
          <template slot="append">
            <el-button @click="handleSelect" icon="el-icon-search">搜索</el-button>
          </template>
        </el-autocomplete>
      </el-col>
      <el-col :offset="6" :span="4" class="add">
        <el-button @click="addProduct" type="primary" icon="el-icon-circle-plus">添加商品</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-table v-loading="load" :data="tableData" max-height="400" style="width: 100%">
        <el-table-column align="center" prop="name" label="商品名称"></el-table-column>
        <el-table-column align="center" prop="price" label="商品价格"></el-table-column>
        <el-table-column align="center" prop="pdesc" label="商品描述"></el-table-column>
        <el-table-column align="center" prop="stock" label="商品库存"></el-table-column>
        <el-table-column align="center" prop="category.name" label="商品类别"></el-table-column>
        <el-table-column align="center" label="商品图片">
          <template slot-scope="scope">
            <img width="60" :src="baseUrl + scope.row.img">
          </template>
        </el-table-column>
        <el-table-column width="200px" fixed="right" label="操作">
          <template slot-scope="Product">
            <el-button-group>
              <el-button
                size="mini"
                title="查看商品"
                @click="showProduct(Product.row)"
                icon="el-icon-search"
              ></el-button>
              <el-button
                size="mini"
                title="修改商品"
                @click="updateProduct(Product.row)"
                type="primary"
                icon="el-icon-edit"
              ></el-button>
              <el-button
                size="mini"
                title="删除商品"
                @click="deleteProduct(Product.row)"
                type="danger"
                icon="el-icon-delete"
              ></el-button>
              <el-button
                v-if="Product.row.state !== 0"
                @click="updateState(Product.row.id, 0)"
                size="mini"
                title="上架商品"
                type="success"
                icon="el-icon-upload2"
              ></el-button>
              <el-button
                v-else
                size="mini"
                title="下架商品"
                @click="updateState(Product.row.id, 1)"
                type="warning"
                icon="el-icon-download"
              ></el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currPage"
        :page-sizes="pageSizes"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <el-dialog @close="categoryClose" title="商品信息" :visible.sync="show" :center="true">
      <el-form inline class="demo-table-expand">
        <el-form-item label="商品名称">
          <span>{{ product.name }}</span>
        </el-form-item>
        <el-form-item label="商品价格">
          <span>{{ product.price }}</span>
        </el-form-item>
        <el-form-item label="商品库存">
          <span>{{ product.stock }}</span>
        </el-form-item>
        <el-form-item label="商品类别">
          <span>{{ product.category.name }}</span>
        </el-form-item>
        <el-form-item label="商品描述">
          <span>{{ product.pdesc }}</span>
        </el-form-item>
        <el-form-item v-if="product.img != null" label="商品图片">
          <img width="60" :src="baseUrl + product.img" alt>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog @closed="restForm" title="修改商品信息" :visible.sync="updateShow" :center="true">
      <el-form :model="upProduct" :rules="rules" status-icon ref="upProduct" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="upProduct.name"></el-input>
        </el-form-item>
        <el-form-item label="商品类别" prop="cid">
          <el-select v-model="upProduct.cid" placeholder="请选择">
            <el-option v-for="item in category" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number :precision="2" :min="1" :step="10" v-model="upProduct.price"></el-input-number>
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number :min="1" :step="100" v-model="upProduct.stock"></el-input-number>
        </el-form-item>
        <el-form-item label="商品描述" prop="pdesc">
          <el-input v-model="upProduct.pdesc"></el-input>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            class="upload-demo"
            :action="baseUrl + '/product/after/upload'"
            ref="upload"
            :on-exceed="imgMax"
            :auto-upload="false"
            :file-list="fileList2"
            :with-credentials="true"
            :limit="1"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传一张jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('upProduct')">修改</el-button>
          <el-button @click="resetForm('upProduct')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog @closed="clearForm('product')" title="添加商品" :visible.sync="addShow" :center="true">
      <el-form :model="product" :rules="rules" status-icon ref="product" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="product.name"></el-input>
        </el-form-item>
        <el-form-item label="商品类别" prop="cid">
          <el-select v-model="product.cid" placeholder="请选择">
            <el-option v-for="item in category" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number :precision="2" :min="1" :step="10" v-model="product.price"></el-input-number>
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number :min="1" :step="100" v-model="product.stock"></el-input-number>
        </el-form-item>
        <el-form-item label="商品描述" prop="pdesc">
          <el-input v-model="product.pdesc"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" prop="img">
          <el-upload
            class="upload-demo"
            :action="baseUrl + '/product/after/upload'"
            ref="upload"
            :on-change="imgChange"
            :on-remove="imgRemove"
            :on-exceed="imgMax"
            :auto-upload="false"
            :file-list="fileList2"
            :with-credentials="true"
            :limit="1"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传一张jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addSubmitForm('product')">添加</el-button>
          <el-button @click="resetForm('product')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Product",
  data: function() {
    return {
      tableData: [],
      pageSizes: [5, 10, 15, 20],
      total: 1,
      search: "",
      currPage: 1,
      pageSize: 5,
      load: true,
      show: false,
      updateShow: false,
      addShow: false,
      fileList2: [],
      param: "",
      category: null,
      product: {
        id: "",
        name: "",
        stock: "",
        cid: "",
        pdesc: "",
        img: null,
        category: {
          name: ""
        }
      },
      upProduct: {
        id: "",
        name: "",
        stock: "",
        cid: "",
        pdesc: "",
        img: null,
        category: {
          name: ""
        }
      },
      empty: {
        id: "",
        name: "",
        stock: "",
        cid: "",
        pdesc: "",
        img: null,
        category: {
          name: ""
        }
      },
      rules: {
        name: [{ required: true, message: "商品名称是必须的" }],
        cid: [{ required: true, message: "商品类别是必须的" }],
        price: [{ required: true, message: "商品价格是必须的" }],
        stock: [{ required: true, message: "商品库存是必须的" }],
        pdesc: [{ required: true, message: "商品描述是必须的" }],
        img: [{ required: true, message: "商品图片是必须的" }]
      }
    };
  },
  created() {
    this.initProduct();
  },
  methods: {
    getCategorys(currPage, pageSize, search) {
      if (search == null) {
        search = "";
      }
      let parames = {
        product: {
          name: search
        },
        myPage: {
          currPage: currPage,
          pageSize: pageSize
        }
      };
      this.$myPost(
        this,
        "/product/after/queryPage",
        (res) => {
          this.tableData = res.data.data.records;
          this.load = false;
          this.total = res.data.data.total;
        },
        parames
      );
    },
    queryCategory() {
      let parames = {
        name: ""
      };
      this.$myPost(
        this,
        "/category/after/byName",
        (res) => {
          this.category = res.data.data;
        },
        parames
      );
    },
    initProduct: function() {
      this.getCategorys(this.currPage, this.pageSize);
    },
    handleCurrentChange(val) {
      this.currPage = val;
      this.getCategorys(val, this.pageSize);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getCategorys(this.currPage, val);
    },
    querySearch: function(queryString, cb) {
      const t = this;
      this.axios
        .post("/product/after/queryByName", {
          name: t.search
        })
        .then(res => {
          cb(res.data.data);
        })
        .catch(error => console.log(error));
    },
    handleSelect: function() {
      this.currPage = 1;
      this.getCategorys(this.currPage, this.pageSize, this.search);
    },
    getTime: function(time) {
      let date = new Date(time);
      return (
        date.getFullYear() +
        "-" +
        (parseInt(date.getMonth()) + 1) +
        "-" +
        date.getDate() +
        " " +
        date.getHours() +
        ":" +
        date.getMinutes() +
        ":" +
        date.getSeconds()
      );
    },
    addProduct: function() {
      this.queryCategory();
      this.addShow = true;
    },
    showProduct(row) {
      this.show = true;
      this.product = row;
    },
    updateProduct(row) {
      this.updateShow = true;
      this.upProduct = this.$copy(row);
      this.queryCategory();
      this.fileList2.push({
        name: "当前图片",
        url: this.baseUrl + row.img
      });
    },
    deleteMethod() {
      this.initProduct();
    },
    deleteProduct(row) {
      this.$myDelete(
        this,
        "/product/after/delete?id=" + row.id,
        this.deleteMethod
      );
    },
    restForm() {
      this.product = this.empty;
      this.fileList2 = [];
    },
    clearForm(formName) {
      this.$refs[formName].resetFields();
    },
    addMethod() {
      this.initProduct();
      this.product = this.empty;
      this.fileList2 = [];
      this.addShow = false;
    },
    updateMethod() {
      this.initProduct();
      this.product = this.empty;
      this.fileList2 = [];
      this.updateShow = false;
    },
    imgChange(file, fileList) {
      console.log(file);
      let imgFile = file.raw;
      this.param = new FormData();
      this.param.append("file", imgFile, imgFile.name);
      this.product.img = "yes";
      this.$refs["product"].validate(valid => {});
      this.$refs["upProduct"].validate(valid => {});
    },
    imgRemove(file, fileList) {
      console.log(1);
      this.product.img = null;
      this.$refs["product"].validate(valid => {});
      this.$refs["upProduct"].validate(valid => {});
    },
    imgMax(file, fileList) {
      this.$message({
        showClose: true,
        message: "最多只能上传一张图片",
        type: "error"
      });
    },
    addSubmitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.param.append("name", this.product.name);
          this.param.append("price", this.product.price);
          this.param.append("stock", this.product.stock);
          this.param.append("cid", this.product.cid);
          this.param.append("pdesc", this.product.pdesc);
          this.$myPost(this, "/product/after/upload", this.addMethod, this.param);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    updateState(id, state) {
      let param = {
        id: id,
        state: state
      };
      this.$myPost(this, "/product/after/updateState", this.updateMethod, param);
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let file = null;
          this.param = new FormData();
          if (this.$refs.upload.uploadFiles[0].raw !== undefined) {
            file = this.$refs.upload.uploadFiles[0].raw;
            this.param.append("file", file, file.name);
          }
          this.param.append("id", this.upProduct.id);
          this.param.append("name", this.upProduct.name);
          this.param.append("price", this.upProduct.price);
          this.param.append("stock", this.upProduct.stock);
          this.param.append("cid", this.upProduct.cid);
          this.param.append("pdesc", this.upProduct.pdesc);
          this.$myPost(
            this,
            "/product/after/update",
            this.updateMethod,
            this.param
          );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    categoryClose() {
      console.log("hello");
      this.product = this.empty;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>

<style scoped>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>